// pages/user/user.js
const app = getApp();
import { userAPI, postAPI } from "../../utils/api.js";
import storageService from "../../utils/storage.js";

Page({
  data: {
    userId: null,
    userInfo: null,
    isCurrentUser: false,
    isFollowed: false,
    posts: [],
    loading: false,
    page: 1,
    hasMore: true,
    activeTab: "posts", // posts, likes, collections
    tabs: [
      { id: "posts", name: "动态", count: 0 },
      { id: "likes", name: "点赞", count: 0 },
      { id: "collections", name: "收藏", count: 0 },
    ],
    stats: {
      posts: 0,
      likes: 0,
      followers: 0,
      following: 0,
    },
  },

  onLoad(options) {
    const userId = options.id || app.globalData.userInfo?.id;
    this.setData({ userId });

    if (userId) {
      this.loadUserInfo();
      this.loadUserPosts();
    }
  },

  onShow() {
    // 检查是否是当前用户
    const currentUserId = app.globalData.userInfo?.id;
    const isCurrentUser = this.data.userId == currentUserId;
    this.setData({ isCurrentUser });
  },

  onPullDownRefresh() {
    this.refreshData();
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMorePosts();
    }
  },

  // 加载用户信息
  loadUserInfo() {
    // 模拟用户数据
    const mockUserInfo = {
      id: this.data.userId,
      nickname: "宠物爱好者",
      avatar: "/images/default-avatar.png",
      level: 2,
      points: 100,
      bio: "热爱宠物，分享美好生活 🐾",
      location: "北京",
      joinTime: "2023-01-01",
      verified: true,
      stats: {
        posts: 25,
        likes: 1280,
        followers: 156,
        following: 89,
      },
    };

    this.setData({
      userInfo: mockUserInfo,
      stats: mockUserInfo.stats,
    });

    // 更新tab计数
    this.updateTabCounts();
  },

  // 加载用户帖子
  loadUserPosts() {
    this.setData({ loading: true });

    // 模拟帖子数据
    const mockPosts = [
      {
        id: 1,
        user: this.data.userInfo,
        content: "今天带我家小猫咪去公园玩，它特别开心！",
        images: ["/images/cat1.jpg", "/images/cat2.jpg"],
        likes: 128,
        comments: 32,
        shares: 15,
        time: "2小时前",
        isLiked: false,
      },
      {
        id: 2,
        user: this.data.userInfo,
        content: "分享一个宠物健康小贴士",
        images: ["/images/health1.jpg"],
        likes: 89,
        comments: 15,
        shares: 8,
        time: "4小时前",
        isLiked: true,
      },
    ];

    this.setData({
      posts: mockPosts,
      loading: false,
    });
  },

  // 刷新数据
  refreshData() {
    this.setData({
      page: 1,
      hasMore: true,
    });

    this.loadUserInfo();
    this.loadUserPosts();

    wx.stopPullDownRefresh();
  },

  // 加载更多帖子
  loadMorePosts() {
    if (!this.data.hasMore) return;

    this.setData({ loading: true });

    setTimeout(() => {
      const newPosts = [
        {
          id: this.data.posts.length + 1,
          user: this.data.userInfo,
          content: "新帖子内容...",
          images: ["/images/pet1.jpg"],
          likes: Math.floor(Math.random() * 100),
          comments: Math.floor(Math.random() * 50),
          shares: Math.floor(Math.random() * 20),
          time: "刚刚",
          isLiked: false,
        },
      ];

      this.setData({
        posts: [...this.data.posts, ...newPosts],
        loading: false,
        page: this.data.page + 1,
        hasMore: this.data.page < 3,
      });
    }, 1000);
  },

  // 切换标签
  switchTab(e) {
    const tabId = e.currentTarget.dataset.tab;
    this.setData({ activeTab: tabId });

    // 根据标签加载不同数据
    this.loadTabData(tabId);
  },

  // 加载标签数据
  loadTabData(tabId) {
    switch (tabId) {
      case "posts":
        this.loadUserPosts();
        break;
      case "likes":
        this.loadLikedPosts();
        break;
      case "collections":
        this.loadCollectedPosts();
        break;
    }
  },

  // 加载点赞的帖子
  loadLikedPosts() {
    // 模拟点赞帖子数据
    const likedPosts = [
      {
        id: 101,
        user: { name: "其他用户", avatar: "/images/avatar2.png" },
        content: "被点赞的帖子内容...",
        images: ["/images/liked1.jpg"],
        likes: 50,
        comments: 10,
        shares: 5,
        time: "1天前",
        isLiked: true,
      },
    ];

    this.setData({ posts: likedPosts });
  },

  // 加载收藏的帖子
  loadCollectedPosts() {
    // 模拟收藏帖子数据
    const collectedPosts = [
      {
        id: 201,
        user: { name: "其他用户", avatar: "/images/avatar3.png" },
        content: "收藏的帖子内容...",
        images: ["/images/collected1.jpg"],
        likes: 30,
        comments: 8,
        shares: 3,
        time: "2天前",
        isLiked: false,
      },
    ];

    this.setData({ posts: collectedPosts });
  },

  // 更新标签计数
  updateTabCounts() {
    const tabs = this.data.tabs.map((tab) => {
      switch (tab.id) {
        case "posts":
          tab.count = this.data.stats.posts;
          break;
        case "likes":
          tab.count = this.data.stats.likes;
          break;
        case "collections":
          tab.count = 12; // 模拟收藏数
          break;
      }
      return tab;
    });

    this.setData({ tabs });
  },

  // 关注/取消关注
  toggleFollow() {
    const isFollowed = !this.data.isFollowed;
    this.setData({ isFollowed });

    if (isFollowed) {
      this.setData({
        "stats.followers": this.data.stats.followers + 1,
      });
      wx.showToast({
        title: "关注成功",
        icon: "success",
      });
    } else {
      this.setData({
        "stats.followers": this.data.stats.followers - 1,
      });
      wx.showToast({
        title: "已取消关注",
        icon: "none",
      });
    }
  },

  // 编辑资料
  editProfile() {
    wx.navigateTo({
      url: "/pages/profile/profile",
    });
  },

  // 设置
  openSettings() {
    wx.navigateTo({
      url: "/pages/settings/settings",
    });
  },

  // 分享用户
  shareUser() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ["shareAppMessage", "shareTimeline"],
    });
  },

  // 发送消息
  sendMessage() {
    wx.navigateTo({
      url: `/pages/chat/chat?userId=${this.data.userId}`,
    });
  },

  // 举报用户
  reportUser() {
    wx.showModal({
      title: "举报用户",
      content: "确定要举报这个用户吗？",
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: "举报成功",
            icon: "success",
          });
        }
      },
    });
  },

  // 帖子点击
  onPostTap(e) {
    const postId = e.currentTarget.dataset.postId;
    wx.navigateTo({
      url: `/pages/detail/detail?id=${postId}`,
    });
  },

  // 点赞帖子
  onLikePost(e) {
    const postId = e.currentTarget.dataset.postId;
    const postIndex = e.currentTarget.dataset.postIndex;

    const posts = this.data.posts;
    const post = posts[postIndex];

    if (post.isLiked) {
      post.likes--;
      post.isLiked = false;
    } else {
      post.likes++;
      post.isLiked = true;
    }

    this.setData({ posts });

    // 保存点赞状态
    storageService.post.setLikeStatus(postId, post.isLiked);
  },
});
